//
// Created by cube on 2020/7/31.
//

#ifndef COMPILERDOMEA1_MAIN_SRC_H
#define COMPILERDOMEA1_MAIN_SRC_H


#include <iostream>
#include <thread>

#include "CRUDPA/CRUDP.h"

using namespace NetBaseCommon;

int port = 4444;

void client(){
    NetAddress addr("127.0.0.1",port);
    NetUdp udp;
    char    buf[2048] = "hello server A";
    while(udp.send(addr,(int8_t*)buf,sizeof(buf)-1) >= 0){
//        std::cout<<"send ok"<<std::endl;
//        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
    std::cout<<"send error"<<std::endl;
}

void server(int id){
    NetAddress addr(INADDR_ANY,port);
    NetAddress cli_addr;
    NetUdp udp;

    int8_t  opt = 1;
    setsockopt(udp.getSocket(),SOL_SOCKET,SO_REUSEADDR,(const char*)&opt,sizeof(opt));

    char    buf[2048] = {};
    buf[1023] = '\0';
    int     r = 0;

    if(udp.bind(addr)){
        do {
//            std::this_thread::sleep_for(std::chrono::seconds(1));
            r = udp.recv(cli_addr,(int8_t*)buf,sizeof(buf)-1,0);
            std::cout<<id<<" recv "<<buf<<std::endl;
        }while (r >= 0);
        std::cout<<id<<"  recv error"<<std::endl;
    }else{
        std::cout<<id<<"  bind error"<<std::endl;
    }
}

void servers(){
    std::vector<std::thread*> ts;
    int count = 2;
    for(int i=0;i<count;i++){
        ts.push_back(new std::thread([&](){server(i);}));
    }
    for(int i=0;i<count;i++)ts[i]->join();
}

#endif //COMPILERDOMEA1_MAIN_SRC_H
